package com.jsu.forum.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsu.forum.mapper.LikeMapper;
import com.jsu.forum.mapper.PassageMapper;
import com.jsu.forum.service.LikeService;
import lombok.extern.slf4j.Slf4j;
import org.example.model.common.dtos.ResponseResult;
import org.example.model.common.enums.RedisCodeEnum;
import org.example.model.common.enums.WebHttpCodeEnum;
import org.example.model.forum.dto.ForumDto;
import org.example.model.forum.dto.LikeDto;
import org.example.model.forum.enums.LikeEnum;
import org.example.model.forum.pojo.Like;
import org.example.model.forum.pojo.Passage;
import org.example.utils.common.IdsUtils;
import org.example.utils.common.RedisCache;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.time.LocalDate;

@Service
@Slf4j
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
    @Autowired
    private PassageServiceImpl passageService;
    @Autowired
    private StringRedisTemplate redisCache;
    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 点赞或取消点赞
     * @param like
     * @return
     */
    @Override
    @Transactional
    public ResponseResult clickLike(@NotNull LikeDto like) {
        int pkId = Integer.parseInt(IdsUtils.creatCode());
        Date now = Date.valueOf(LocalDate.now());
        Like like1 = new Like(pkId, like.getPassageId(), like.getUserId(),now);
        if (like.getState().equals(LikeEnum.LIKE.getNum())) {
            //该文章点赞数加1
            if (passageService.addLike(like.getPassageId())) {
                //更新到redis中的点赞点赞数
                String passageKey = RedisCodeEnum.FORUM_PASSAGE.getMsg()+like1.getPassageId();
                String passageJson = redisCache.opsForValue().get(passageKey);
                ForumDto passage = null;
                //读取passage
                try {
                    passage = mapper.readValue(passageJson, ForumDto.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                //更新点赞数
                passage.setLikeCount(passage.getLikeCount()+1);
                //删除原先的记录
                redisCache.opsForValue().getOperations().delete(passageKey);
                try {
                    passageJson = mapper.writeValueAsString(passage);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                //存储新的记录
                redisCache.opsForValue().set(passageKey,passageJson);
                //存储redis中的记录
                String json = null;
                try {
                    json = mapper.writeValueAsString(like1);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                //存储点赞记录
                String key = RedisCodeEnum.PASSAGE_LIKE.getMsg()+like1.getPkId();
                redisCache.opsForValue().set(key,json);
                //存储到数据库中
                int count = getBaseMapper().insert(like1);
                if (count<=0) {
                    return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"点击失败");
                }
            }
            return ResponseResult.errorResult(WebHttpCodeEnum.SUCCESS,"点赞成功");
        }else {
            //该文章点赞数减一
            if(passageService.reduceLike(like.getPassageId())){
                Like like2 = getBaseMapper().selectByPassageIdAndUserId(like.getPassageId(), like.getUserId());
                //删除redis点赞记录
                String key = RedisCodeEnum.PASSAGE_LIKE.getMsg()+like2.getPkId();
                redisCache.opsForValue().getOperations().delete(key);
                //删除数据库中的点赞记录
                int count = getBaseMapper().deleteByPassageIdAndUserId(like.getPassageId(), like.getUserId());
                if (count<=0) {
                    return ResponseResult.errorResult(WebHttpCodeEnum.FAIL,"删除点赞记录失败");
                }

                //文章点赞数减一
                //更新到redis中的点赞点赞数
                String passageKey = RedisCodeEnum.FORUM_PASSAGE.getMsg()+like1.getPassageId();
                String passageJson = redisCache.opsForValue().get(passageKey);
                ForumDto passage = null;
                //读取passage
                try {
                    passage = mapper.readValue(passageJson, ForumDto.class);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

                //更新点赞数
                passage.setLikeCount(passage.getLikeCount()-1);
                //删除原先的记录
                redisCache.opsForValue().getOperations().delete(passageKey);
                try {
                    passageJson = mapper.writeValueAsString(passage);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                //存储新的记录
                redisCache.opsForValue().set(passageKey,passageJson);
            }
            return ResponseResult.errorResult(WebHttpCodeEnum.SUCCESS,"取消点赞成功");
        }

    }
}
